#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
查找Chrome浏览器安装路径的工具
"""

import os
import winreg  # 用于访问Windows注册表


def find_chrome_path():
    """在Windows系统中查找Chrome浏览器的安装路径"""
    possible_paths = []
    
    # 常见的Chrome安装路径 - 使用原始字符串处理反斜杠
    default_paths = [
        os.path.join(os.environ.get('PROGRAMFILES', r'C:\Program Files'), 'Google', 'Chrome', 'Application', 'chrome.exe'),
        os.path.join(os.environ.get('PROGRAMFILES(X86)', r'C:\Program Files (x86)'), 'Google', 'Chrome', 'Application', 'chrome.exe'),
        os.path.join(os.environ.get('LOCALAPPDATA', r'C:\Users\USERNAME\AppData\Local'), 'Google', 'Chrome', 'Application', 'chrome.exe'),
    ]
    
    # 添加用户配置文件路径（需要替换用户名）
    if 'USERNAME' in os.environ:
        user_path = os.path.join(r'C:\Users', os.environ['USERNAME'], 'AppData', 'Local', 'Google', 'Chrome', 'Application', 'chrome.exe')
        default_paths.append(user_path)
    
    # 检查默认路径
    for path in default_paths:
        if os.path.exists(path):
            possible_paths.append(path)
    
    # 从注册表中查找Chrome路径
    try:
        # 尝试从注册表中读取Chrome的安装路径
        reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'
        
        # 先检查HKEY_LOCAL_MACHINE
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
            path = winreg.QueryValue(key, None)
            if os.path.exists(path):
                possible_paths.append(path)
            winreg.CloseKey(key)
        except WindowsError:
            pass
        
        # 再检查HKEY_CURRENT_USER
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path)
            path = winreg.QueryValue(key, None)
            if os.path.exists(path):
                possible_paths.append(path)
            winreg.CloseKey(key)
        except WindowsError:
            pass
        
        # 检查Chrome安装目录
        try:
            reg_path = r'SOFTWARE\Google\Chrome\BLBeacon'
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path)
            version = winreg.QueryValueEx(key, 'version')[0]
            winreg.CloseKey(key)
            
            # 尝试根据版本号构建路径
            possible_chrome_paths = [
                os.path.join(os.environ.get('PROGRAMFILES', r'C:\Program Files'), 'Google', 'Chrome', 'Application', 'chrome.exe'),
                os.path.join(os.environ.get('LOCALAPPDATA', r'C:\Users\USERNAME\AppData\Local'), 'Google', 'Chrome', 'Application', 'chrome.exe'),
            ]
            
            for path in possible_chrome_paths:
                if os.path.exists(path):
                    possible_paths.append(path)
        except WindowsError:
            pass
    except Exception as e:
        print(f"读取注册表时出错: {e}")
    
    # 去重
    possible_paths = list(set(possible_paths))
    
    return possible_paths


def main():
    """主函数"""
    print("正在查找Chrome浏览器的安装路径...")
    chrome_paths = find_chrome_path()
    
    if chrome_paths:
        print(f"找到 {len(chrome_paths)} 个可能的Chrome浏览器路径:")
        for i, path in enumerate(chrome_paths, 1):
            print(f"{i}. {path}")
        
        print("\n请使用以下命令运行小米便签导出工具（选择其中一个路径）:")
        for path in chrome_paths:
            # 对路径中的反斜杠进行转义，以便在命令行中使用
            escaped_path = path.replace('\\', '\\\\')
            print(f'python mi_note_web_exporter.py --driver_path "C:\\Program Files\\chrome\\chromedriver.exe" --chrome_path "{escaped_path}"')
    else:
        print("未找到Chrome浏览器。请手动安装Chrome浏览器，或确认其安装位置。")
    
    print("\n如果找不到，请手动查找Chrome浏览器的安装位置，并使用上述命令格式运行导出工具。")


if __name__ == '__main__':
    main()